import { Directive, ElementRef, Input } from '@angular/core';
//Controls
import { AmChartsService } from "@amcharts/amcharts3-angular";

@Directive({
    selector: '[intervalChart]'
})
export class IntervalChartDirective {
    private chart: any;

    private _currentClusterName: string;
    private _companyCode: string;
    private _clusters: any[];

    private _chartData: number = 0;
    private _graphs: any[] = [];
    private _values: any = {};

    @Input() chartID: string;
    @Input() set companyCode(value: string) {
        //reset graph name
        if (this._currentClusterName) {
            for (var i = 0; i < this._clusters.length; i++) {
                if (this._clusters[i].code == this._companyCode) {
                    this._clusters[i].shortName = this._currentClusterName;
                }
            }
        }

        this._companyCode = value;
        if (this.chart) {
            this._graphs = [];
            this.clusters = this._clusters;
        }
    }

    @Input() set clusters(value: any[]) {
        if (value) {
            this._clusters = value;
            //get cluster count and set size for each cluster from total of 100
            for (var i = 0; i < value.length; i++) {
                if (value[i].code == this._companyCode) {
                    this._currentClusterName = value[i].shortName;
                    value[i].shortName = '';
                }

                //add graphs
                this._graphs.push({
                    fillAlphas: 1,
                    showBalloon: false,
                    type: "column",
                    labelText: value[i].shortName,
                    labelPosition: "middle",
                    lineColor: value[i].color,
                    valueField: value[i].code,
                    axisLabel: (i == 0 ? 0 : value[i - 1].topInterval) + '-' + value[i].topInterval,
                });
                //set graph values
                this._values[value[i].code] = 100 / value.length;
            }
            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.chart.dataProvider = [this._values];
                    this.chart.graphs = this._graphs;
                });

                this.buildAxis(this.chart.categoryAxis.x);
            }
        }
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService) { }

    ngOnInit() {
        //prepare chart using the input risk levels
        this.chart = this.AmCharts.makeChart(this.chartID, {
            type: "serial",
            autoMargins: false,
            addClassNames: true,
            marginTop: 12,
            marginLeft: 0,
            marginBottom: 25,
            marginRight: 0,
            valueAxes: [{
                stackType: "regular",
                gridAlpha: 0,
                axisAlpha: 0,
                maximum: 100,
                labelsEnabled: false
            }],
            dataProvider: [this._values],
            startDuration: 0, //animation disabled because of angular2-ie9-shims making it slow
            graphs: this._graphs,
            rotate: true,
            columnWidth: 1,
            categoryAxis: {
                gridAlpha: 0,
                axisAlpha: 0,
                labelsEnabled: false
            },
            listeners: [{
                event: "rendered",
                method: (e) => {
                    if (this.chart == undefined) this.chart = e.chart;
                    if (this._values) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            },
            {
                event: "resized",
                method: (e) => {
                    this.buildAxis(e.chart.categoryAxis.x);
                }
            }]
        });
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }

    private buildAxis(startLocation: number): void {
        if (this.chart.valueAxes.length == 0 || this.chart.valueAxes[0].data == undefined) return;

        var minInterval = 0;
        var htmlContent = '', style = '', textStyle = '', distributionTextDiv = '';
        var element = document.createElement('canvas');
        var context = element.getContext("2d");
        context.font = "14px Calibri";

        //#FML
        var graphs = this.chart.valueAxes[0].data[0].axes[this.chart.valueAxes[0].id].graphs;
        var graphElements = Object.keys(graphs);

        Object.keys(graphs).forEach(element => {
            if (graphs[element].graph.type == 'column') {
                style = 'float: left;height: 100%;';
                textStyle = 'text-align: center;font-size: 8pt;margin:0px;';

                if (graphs[element].graph.valueField == this._companyCode) {
                    //style += 'font-weight: 900;';             
                    var className = "amcharts-graph-" + graphs[element].graph.id;
                    var items = document.getElementsByClassName(className);
                    items[0].parentElement.style.backgroundColor = "black";
                }

                if (graphs[element].values.open == 0)
                    style += 'margin-left:' + startLocation + 'px;';

                style += 'width:' + graphs[element].columnWidth + 'px;';

                let text = graphs[element].graph.axisLabel;

                distributionTextDiv = `<p class="text-center chart-legend" style="${textStyle}">${text}</p>`;

                htmlContent += "<div style='" + style + "'>" + distributionTextDiv + "</div>";
            }
        }, this);

        this.el.nativeElement.children.intervalChartAxis.innerHTML = htmlContent;
        this.selectCluster(startLocation);
    }

    private selectCluster(startLocation: number): void {
        let borderWidth = 3;
        let leftPosition = this._companyCode;

        var graphs = this.chart.valueAxes[0].data[0].axes[this.chart.valueAxes[0].id].graphs;
        var graphElements = Object.keys(graphs);
        Object.keys(graphs).forEach((element, index) => {
            if (graphs[element].graph.valueField == this._companyCode) {
                let style = 'border: ' + borderWidth + 'px black solid; width: ' + (graphs[element].columnWidth + borderWidth) + 'px; height:' + (graphs[element].columnHeight + borderWidth / 2) + 'px;';
                style += "left:" + (graphs[element].graph.x + (index * graphs[element].columnWidth)) + "px;top:" + graphs[element].graph.y + "px;";

                let textHtml = "<span style='display:block;vertical-align:middle;text-align:center;line-height:" + (graphs[element].columnHeight - borderWidth) + "px'><b>" + this._currentClusterName + "</b></span>";
                let htmlContent = "<div style='position: absolute;" + style + "'>" + textHtml + "</div>";
                this.el.nativeElement.children.intervalChartAxis.innerHTML += htmlContent;
                return;
            }
        })
    }
}